import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Form,
  Input,
  Select,
  DatePicker,
  Button,
  Space,
  Tag,
  Row,
  Col,
  Descriptions,
  Modal,
  Timeline,
  Badge,
  Alert,
  Statistic,
  message
} from 'antd';
import {
  SearchOutlined,
  EyeOutlined,
  UserOutlined,
  DesktopOutlined,
  MobileOutlined,
  ApiOutlined,
  FileTextOutlined,
  ExportOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import { logAPI } from '../../services/api';
import { useAdminAuth } from '../../hooks/useAuth';

const { Option } = Select;
const { RangePicker } = DatePicker;

const AdminLogs = () => {
  const [loading, setLoading] = useState(false);
  const [logs, setLogs] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0
  });
  const [searchForm] = Form.useForm();
  const [detailVisible, setDetailVisible] = useState(false);
  const [selectedLog, setSelectedLog] = useState(null);
  const [statistics, setStatistics] = useState({
    today: 0,
    week: 0,
    month: 0,
    total: 0
  });
  const { hasAdminPermission } = useAdminAuth();

  // 统一的按钮样式
  const buttonStyle = {
    height: '32px',
    fontSize: '14px',
    fontWeight: '400',
    borderRadius: '6px'
  };

  useEffect(() => {
    loadLogs();
    loadStatistics();
  }, []);

  const loadLogs = async (params = {}) => {
    setLoading(true);
    try {
      const response = await logAPI.getLogs({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...params
      });
      
      if (response.success) {
        setLogs(response.data.list);
        setPagination(prev => ({
          ...prev,
          total: response.data.total
        }));
      }
    } catch (error) {
      console.error('加载日志失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadStatistics = async () => {
    try {
      const response = await logAPI.getLogStatistics();
      if (response.success) {
        setStatistics(response.data);
      }
    } catch (error) {
      console.error('加载统计数据失败:', error);
    }
  };

  const handleSearch = () => {
    const values = searchForm.getFieldsValue();
    setPagination(prev => ({ ...prev, current: 1 }));
    loadLogs(values);
  };

  const handleReset = () => {
    searchForm.resetFields();
    setPagination(prev => ({ ...prev, current: 1 }));
    loadLogs();
  };

  const handleRefresh = () => {
    loadLogs();
    loadStatistics();
  };

  const handleViewDetail = (log) => {
    setSelectedLog(log);
    setDetailVisible(true);
  };

  const handleExport = () => {
    const values = searchForm.getFieldsValue();
    // 这里应该调用导出API
    message.info('正在导出日志...');
  };

  const getActionTypeConfig = (type) => {
    const typeMap = {
      'login': { color: 'green', text: '登录', icon: <UserOutlined /> },
      'logout': { color: 'orange', text: '登出', icon: <UserOutlined /> },
      'create': { color: 'blue', text: '创建', icon: <FileTextOutlined /> },
      'update': { color: 'cyan', text: '更新', icon: <FileTextOutlined /> },
      'delete': { color: 'red', text: '删除', icon: <FileTextOutlined /> },
      'view': { color: 'default', text: '查看', icon: <EyeOutlined /> },
      'export': { color: 'purple', text: '导出', icon: <ExportOutlined /> },
      'import': { color: 'magenta', text: '导入', icon: <FileTextOutlined /> }
    };
    return typeMap[type] || { color: 'default', text: type };
  };

  const getModuleConfig = (module) => {
    const moduleMap = {
      'system': { color: 'red', text: '系统' },
      'user': { color: 'orange', text: '用户' },
      'product': { color: 'green', text: '商品' },
      'order': { color: 'blue', text: '订单' },
      'category': { color: 'purple', text: '分类' },
      'role': { color: 'cyan', text: '角色' },
      'permission': { color: 'magenta', text: '权限' },
      'refund': { color: 'gold', text: '售后' }
    };
    return moduleMap[module] || { color: 'default', text: module };
  };

  const getDeviceIcon = (device) => {
    if (device?.includes('Mobile')) return <MobileOutlined />;
    if (device?.includes('API')) return <ApiOutlined />;
    return <DesktopOutlined />;
  };

  const columns = [
    {
      title: '操作时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 160,
      render: (time) => new Date(time).toLocaleString(),
    },
    {
      title: '操作人',
      dataIndex: 'operator',
      key: 'operator',
      width: 120,
      render: (operator) => (
        <Space>
          <UserOutlined />
          <span>{operator}</span>
        </Space>
      ),
    },
    {
      title: '模块',
      dataIndex: 'module',
      key: 'module',
      width: 100,
      render: (module) => {
        const config = getModuleConfig(module);
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '操作类型',
      dataIndex: 'action',
      key: 'action',
      width: 100,
      render: (action) => {
        const config = getActionTypeConfig(action);
        return (
          <Tag icon={config.icon} color={config.color}>
            {config.text}
          </Tag>
        );
      },
    },
    {
      title: '操作内容',
      dataIndex: 'content',
      key: 'content',
      ellipsis: true,
      render: (content) => (
        <span style={{ fontSize: '12px' }}>{content}</span>
      ),
    },
    {
      title: 'IP地址',
      dataIndex: 'ipAddress',
      key: 'ipAddress',
      width: 120,
    },
    {
      title: '设备',
      dataIndex: 'device',
      key: 'device',
      width: 80,
      render: (device) => (
        <span style={{ fontSize: '18px' }}>
          {getDeviceIcon(device)}
        </span>
      ),
    },
    {
      title: '结果',
      dataIndex: 'result',
      key: 'result',
      width: 80,
      render: (result) => (
        <Badge
          status={result === 'success' ? 'success' : 'error'}
          text={result === 'success' ? '成功' : '失败'}
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 100,
      render: (_, record) => (
        <Button
          type="link"
          icon={<EyeOutlined />}
          size="small"
          onClick={() => handleViewDetail(record)}
          style={buttonStyle}
        >
          详情
        </Button>
      ),
    },
  ];

  return (
    <div>
      {/* 统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 16 }}>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="今日操作"
              value={statistics.today}
              valueStyle={{ color: '#3f8600' }}
              loading={loading}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="本周操作"
              value={statistics.week}
              valueStyle={{ color: '#1890ff' }}
              loading={loading}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="本月操作"
              value={statistics.month}
              valueStyle={{ color: '#cf1322' }}
              loading={loading}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="总操作数"
              value={statistics.total}
              loading={loading}
            />
          </Card>
        </Col>
      </Row>

      {/* 搜索表单 */}
      <Card style={{ marginBottom: 16 }}>
        <Form
          form={searchForm}
          layout="horizontal"
          onFinish={handleSearch}
        >
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item name="operator" label="操作人">
                <Input placeholder="请输入操作人" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="module" label="模块">
                <Select placeholder="选择模块" allowClear>
                  <Option value="system">系统</Option>
                  <Option value="user">用户</Option>
                  <Option value="product">商品</Option>
                  <Option value="order">订单</Option>
                  <Option value="category">分类</Option>
                  <Option value="role">角色</Option>
                  <Option value="permission">权限</Option>
                  <Option value="refund">售后</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="action" label="操作类型">
                <Select placeholder="选择操作类型" allowClear>
                  <Option value="login">登录</Option>
                  <Option value="logout">登出</Option>
                  <Option value="create">创建</Option>
                  <Option value="update">更新</Option>
                  <Option value="delete">删除</Option>
                  <Option value="view">查看</Option>
                  <Option value="export">导出</Option>
                  <Option value="import">导入</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="result" label="结果">
                <Select placeholder="选择结果" allowClear>
                  <Option value="success">成功</Option>
                  <Option value="fail">失败</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="dateRange" label="操作时间">
                <RangePicker style={{ width: '100%' }} showTime />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="ipAddress" label="IP地址">
                <Input placeholder="请输入IP地址" />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Space>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  icon={<SearchOutlined />}
                  style={buttonStyle}
                >
                  搜索
                </Button>
                <Button onClick={handleReset} style={buttonStyle}>重置</Button>
                <Button 
                  icon={<ReloadOutlined />} 
                  onClick={handleRefresh}
                  style={buttonStyle}
                >
                  刷新
                </Button>
              </Space>
            </Col>
          </Row>
        </Form>
      </Card>

      {/* 日志列表 */}
      <Card 
        title="操作日志"
        extra={
          hasAdminPermission('log:export') && (
            <Button 
              icon={<ExportOutlined />} 
              onClick={handleExport}
              style={buttonStyle}
            >
              导出日志
            </Button>
          )
        }
      >
        <Alert
          message="数据保留说明"
          description="系统日志数据默认保留90天，超过90天的日志将自动归档。如需查询历史日志，请联系系统管理员。"
          type="info"
          showIcon
          closable
          style={{ marginBottom: 16 }}
        />

        <Table
          columns={columns}
          dataSource={logs}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({ ...prev, current: page, pageSize }));
              loadLogs({ page, pageSize });
            },
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      {/* 日志详情模态框 */}
      <Modal
        title="日志详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailVisible(false)} style={buttonStyle}>
            关闭
          </Button>
        ]}
        width={700}
      >
        {selectedLog && (
          <div>
            <Descriptions bordered column={2} style={{ marginBottom: 24 }}>
              <Descriptions.Item label="日志ID">
                {selectedLog.id}
              </Descriptions.Item>
              <Descriptions.Item label="操作时间">
                {new Date(selectedLog.createTime).toLocaleString()}
              </Descriptions.Item>
              <Descriptions.Item label="操作人">
                {selectedLog.operator}
              </Descriptions.Item>
              <Descriptions.Item label="操作人ID">
                {selectedLog.operatorId || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="模块">
                <Tag color={getModuleConfig(selectedLog.module).color}>
                  {getModuleConfig(selectedLog.module).text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="操作类型">
                <Tag 
                  icon={getActionTypeConfig(selectedLog.action).icon}
                  color={getActionTypeConfig(selectedLog.action).color}
                >
                  {getActionTypeConfig(selectedLog.action).text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="IP地址">
                {selectedLog.ipAddress}
              </Descriptions.Item>
              <Descriptions.Item label="地理位置">
                {selectedLog.location || '未知'}
              </Descriptions.Item>
              <Descriptions.Item label="设备信息" span={2}>
                {selectedLog.device || '未知设备'}
              </Descriptions.Item>
              <Descriptions.Item label="浏览器" span={2}>
                {selectedLog.browser || '未知浏览器'}
              </Descriptions.Item>
              <Descriptions.Item label="操作结果">
                <Badge
                  status={selectedLog.result === 'success' ? 'success' : 'error'}
                  text={selectedLog.result === 'success' ? '成功' : '失败'}
                />
              </Descriptions.Item>
              <Descriptions.Item label="耗时">
                {selectedLog.duration || 0} ms
              </Descriptions.Item>
              <Descriptions.Item label="操作内容" span={2}>
                {selectedLog.content}
              </Descriptions.Item>
              {selectedLog.errorMessage && (
                <Descriptions.Item label="错误信息" span={2}>
                  <span style={{ color: '#f5222d' }}>{selectedLog.errorMessage}</span>
                </Descriptions.Item>
              )}
            </Descriptions>

            {selectedLog.requestData && (
              <>
                <h4>请求数据</h4>
                <pre style={{ 
                  background: '#f5f5f5', 
                  padding: '12px', 
                  borderRadius: '4px',
                  overflow: 'auto',
                  maxHeight: '200px'
                }}>
                  {JSON.stringify(selectedLog.requestData, null, 2)}
                </pre>
              </>
            )}

            {selectedLog.responseData && (
              <>
                <h4>响应数据</h4>
                <pre style={{ 
                  background: '#f5f5f5', 
                  padding: '12px', 
                  borderRadius: '4px',
                  overflow: 'auto',
                  maxHeight: '200px'
                }}>
                  {JSON.stringify(selectedLog.responseData, null, 2)}
                </pre>
              </>
            )}

            <h4>操作轨迹</h4>
            <Timeline>
              <Timeline.Item color="green">
                {new Date(selectedLog.createTime).toLocaleString()} - 开始操作
              </Timeline.Item>
              {selectedLog.steps?.map((step, index) => (
                <Timeline.Item key={index} color={step.success ? 'blue' : 'red'}>
                  {step.time} - {step.action}
                </Timeline.Item>
              ))}
              <Timeline.Item color={selectedLog.result === 'success' ? 'green' : 'red'}>
                {new Date(selectedLog.createTime).toLocaleString()} - 
                操作{selectedLog.result === 'success' ? '成功' : '失败'}
                （耗时 {selectedLog.duration || 0}ms）
              </Timeline.Item>
            </Timeline>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default AdminLogs;